package top.zywork.common;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import top.zywork.enums.AesAlgorithmEnum;
import top.zywork.enums.CharsetEnum;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Security;

/**
 * AES加密解密类<br/>
 * <p>
 * 创建于2020-08-21
 *
 * @author 王振宇
 * @version 1.0
 */
@Slf4j
public class AesUtils {

    public static String encode(String data, String key, AesAlgorithmEnum aesAlgorithmEnum) {
        Security.addProvider(new BouncyCastleProvider());
        String md5Key = DigestUtils.md5Hex(key).toLowerCase();
        SecretKeySpec keySpec = new SecretKeySpec(md5Key.getBytes(), AesAlgorithmEnum.AES.getValue());
        try {
            Cipher cipher = Cipher.getInstance(aesAlgorithmEnum.getValue());
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
            byte[] encode = Base64.encodeBase64(cipher.doFinal(data.getBytes()));
            return new String(encode, CharsetEnum.UTF8.getValue());
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | BadPaddingException
                | UnsupportedEncodingException | IllegalBlockSizeException | InvalidKeyException e) {
            log.error("aes encode error: {}", e.getMessage());
            throw ExceptionUtils.commonException("AES编码错误", e);
        }
    }


    public static String decode(String data, String key, AesAlgorithmEnum aesAlgorithmEnum) {
        Security.addProvider(new BouncyCastleProvider());
        byte[] decodeBase64 = Base64.decodeBase64(data);
        String md5Key = DigestUtils.md5Hex(key).toLowerCase();
        try {
            Cipher cipher = Cipher.getInstance(aesAlgorithmEnum.getValue());
            SecretKey keySpec = new SecretKeySpec(md5Key.getBytes(), AesAlgorithmEnum.AES.getValue());
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            byte[] decoded = cipher.doFinal(decodeBase64);
            return new String(decoded, CharsetEnum.UTF8.getValue());
        }catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException | BadPaddingException | UnsupportedEncodingException | IllegalBlockSizeException e) {
            log.error("aes decode error: {}", e.getMessage());
            throw ExceptionUtils.commonException("AES解码错误", e);
        }
    }

}
